package com.naiterui.ehp.bp.security.utils;

import com.naiterui.ehp.bp.security.exception.BadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 获取当前登录的用户
 */
@Slf4j
public class SecurityUtils {

  /**
   * 获取当前登录的用户
   *
   * @return UserDetails
   */
  public static <T extends BaseJwtUser> T getCurrentUser() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication == null) {
      throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");
    }
    //noinspection unchecked
    return (T) authentication.getPrincipal();
  }

  /**
   * 获取系统用户名称
   *
   * @return 系统用户名称
   */
  public static String getCurrentUsername() {
    return SecurityUtils.getCurrentUser().getUsername();
  }

}
